import { useState } from "react"
import SyntaxHighlighter from '@/components/SyntaxHighlighter'


const debounceFn = (fn, wait) => {
  let timer = null

  return function (...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, wait)
  }
}

const consoleFn = debounceFn(() => {
  console.log('我是通过 debounceFn 实现的')
}, 1000)

const code1 = `
  let timer = null

  function AntiShake() {
    const [value, setValue] = useState('')
    const [text, setText] = useState('')
    

    // 防抖
    const debounce = (fn) => {
      if (timer) {
        clearTimeout(timer)
      }

      timer = setTimeout(() => {
        fn()
      }, 1000)
    }
    
    const handleChange = (e) => {
      setValue(e.target.value)

      debounce(() => {
        setText('等停止输入超过一定时间后显示的内容')
      })
    }

    return (
      <div>
        <p>手写一个防抖函数</p>
        <input
          placeholder="请输入搜索类容"
          value={value}
          onChange={handleChange}
        />
        <p>输入框输入的内容，防抖处理过的：{ text }</p>
        <button onClick={() => setText('')}>清除内容</button>
      </div>
    )
  }
`

let timer = null

function AntiShake() {
  const [value, setValue] = useState('')
  const [text, setText] = useState('')
  

  // 防抖
  const debounce = (fn) => {
    if (timer) {
      clearTimeout(timer)
    }

    timer = setTimeout(() => {
      fn()
    }, 1000)
  }
  
  const handleChange = (e) => {
    setValue(e.target.value)

    debounce(() => {
      setText('等停止输入超过一定时间后显示的内容')
    })
  }

  const handleClick = () => {
    consoleFn()
  }

  return (
    <div>
      <p>手写一个防抖函数</p>
      <input
        placeholder="请输入搜索类容"
        value={value}
        onChange={handleChange}
      />
      <p>输入框输入的内容，防抖处理过的：{ text }</p>
      <button onClick={() => setText('')}>清除内容</button>

      <p>控制台里是使用封装成方法的实现，查看点击按钮后的打印效果：</p>
      <button onClick={handleClick}>查看控制打印效果</button>
      <p>代码实现逻辑：</p>
      <SyntaxHighlighter children={code1} />
      
    </div>
  )
}

export default AntiShake